﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Data;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for ProductionOrder.xaml
    /// </summary>
    public partial class YCAEK03DOC : DocumentBase
    {
        #region-------------Properties-----------------------
        ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        INTEXDBC INTEXDBC
        {
            get
            {
                return app.INTEXDBC;
            }
        }
        INTEXBL INTEXBL
        {
            get
            {
                return app.INTEXBL;
            }
        }
        public YCAEK03DOCData m_Data;
        ITXEXRPT ITXEXRPT;
        bool IsSupplierLoded = false;
        public string PrnType = "EXCEL";
        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData");
            }
        }

        public SETINTEXDB SetEnv
        {
            get
            {
                return (SETINTEXDB)TryFindResource("Set4ITX");
            }
        }
        public SETINTEXDB Set4ITX
        {
            get
            {
                return (SETINTEXDB)TryFindResource("Set4ITX");
            }
        }
        public SETINTEXDB SetDetail
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetDetail");
            }
        }
        public string ToApply
        {
            get
            {
                return txtApply.Text;
            }
        }

        #region=====vwLIEFDAT=======
        CollectionViewSource vwLIEFDAT
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwLIEFDAT");
            }
        }
        DataRow dwLIEFDAT
        {
            get
            {
                if (vwLIEFDAT.View == null)
                    return null;
                if ((DataRowView)vwLIEFDAT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwLIEFDAT.View.CurrentItem).Row;
            }
        }
        #endregion

        #region=====vwTEKKOPF=======
        CollectionViewSource vwTEKKOPF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwTEKKOPF");
            }
        }
        DataRow dwTEKKOPF
        {
            get
            {
                if (vwTEKKOPF.View == null)
                    return null;
                if ((DataRowView)vwTEKKOPF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwTEKKOPF.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwEKKOPF=======
        CollectionViewSource vwEKKOPF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwEKKOPF");
            }
        }
        DataRow dwEKKOPF
        {
            get
            {
                if (vwEKKOPF.View == null)
                    return null;
                if ((DataRowView)vwEKKOPF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwEKKOPF.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwEKPOS=======
        CollectionViewSource vwEKPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwEKPOS");
            }
        }
        DataRow dwEKPOS
        {
            get
            {
                if (vwEKPOS.View == null)
                    return null;
                if ((DataRowView)vwEKPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwEKPOS.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwABAUFM=======
        CollectionViewSource vwABAUFM
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwABAUFM");
            }
        }
        DataRow dwABAUFM
        {
            get
            {
                if (vwABAUFM.View == null)
                    return null;
                if ((DataRowView)vwABAUFM.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwABAUFM.View.CurrentItem).Row;
            }
        }
        #endregion
        bool IsChkALL
        {
            get
            {
                if (ChkALL.IsChecked == true)
                {
                    return true;
                }
                return false;
            }
            set
            {
                if (value)
                {
                    ChkALL.IsChecked = true;
                }
                else
                {
                    ChkALL.IsChecked = false;
                }
            }
        }
        bool IsChkEKPBEKZ
        {
            get
            {
                if (ChkEKPBEKZ.IsChecked == true)
                {
                    return true;
                }
                return false;
            }
            set
            {
                if (value)
                {
                    ChkEKPBEKZ.IsChecked = true;
                }
                else
                {
                    ChkEKPBEKZ.IsChecked = false;
                }
            }
        }
        bool IsCheckPayment
        {
            get
            {
                if (ChkPayment.IsChecked == true)
                {
                    return true;
                }
                return false;
            }
            set
            {
                if (value)
                {
                    ChkPayment.IsChecked = true;
                }
                else
                {
                    ChkPayment.IsChecked = false;
                }
            }
        }
        bool IsChkNoControl
        {
            get
            {
                if (ChkNoControl.IsChecked == true)
                {
                    return true;
                }
                return false;
            }
            set
            {
                if (value)
                {
                    ChkNoControl.IsChecked = true;
                }
                else
                {
                    ChkNoControl.IsChecked = false;
                }
            }
        }

        bool IsChkEKPKNTRNRL
        {
            get
            {
                if (ChkEKPKNTRNRL.IsChecked == true)
                {
                    return true;
                }
                return false;
            }
            set
            {
                if (value)
                {
                    ChkEKPKNTRNRL.IsChecked = true;
                }
                else
                {
                    ChkEKPKNTRNRL.IsChecked = false;
                }
            }
        }
        public string KRS
        {
            get
            {
                return m_Data.Right("  " + txtABPAUFKRS.Text.ToString().Trim(), 2);
            }
            set
            {
                txtABPAUFKRS.Text = value;
            }
        }
        public string LFD
        {
            get
            {
                return m_Data.Right("000000" + txtABPAUFLFD.Text.ToString().Trim(), 6); ;
            }
            set
            {
                txtABPAUFLFD.Text = value;
            }
        }
        BindingListCollectionView cvABA
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgABA.ItemsSource);
            }
        }
        #endregion
        public YCAEK03DOC()
        {
            InitializeComponent();
            this.Name = "采购单打印";
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            InitializeComponent();
            m_Data = new YCAEK03DOCData();
            ITXEXRPT = new ITXEXRPT();
            ITXEXRPT.Root = "C:\\IntexReport";
            ITXEXRPT.strCompany = app.company;
            ITXEXRPT.PrintType = "OpenExcel";
            if (app.User.Trim() == "YCAV")
            {
                txtABPAUFKRS.Text = "WP";
                txtABPAUFLFD.Text = "001613";
            }
            IsChkALL = true;
            IsChkEKPBEKZ = false;
            IsChkEKPKNTRNRL = false;
            butSTARTAPP.IsEnabled = false;
            butENDAPP.IsEnabled = false;
            btnPrint.IsEnabled = false;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                SetEnv.Clear();
                if (!IsSupplierLoded)
                {
                    SetEnv.Merge(m_Data.LoadEnv());
                    IsSupplierLoded = true;
                }
                if (IsLoaded)
                    return;
                IsLoaded = true;
                vwEKPOS.View.CurrentChanged += vwEKPOS_CurrentChanged;
                vwEKKOPF.View.CurrentChanged += vwEKKOPF_CurrentChanged;
                vwLIEFDAT.View.CurrentChanged += vwLIEFDAT_CurrentChanged;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;

        }
        void vwEKPOS_CurrentChanged(object sender, EventArgs e)
        {
            if (dwEKPOS == null)
            {
                cvABA.CustomFilter = null;
                return;
            }
            string filter = "ABAAUFKRS='" + dwEKPOS["EKPAUFKRS"].ToString() + "' AND ABAAUFLFD='" + dwEKPOS["EKPAUFLFD"].ToString() + "' AND ABAAUFPOS='" + dwEKPOS["EKPAUFPOS"].ToString() + "'";
            cvABA.CustomFilter = filter;
            txtLastApp.Text = "N";
            if (dwEKPOS["EKPLSCOL"].ToString().Trim() == "Y")
            {
                txtLastApp.Text = "Y";
            }
                
        }
        void vwLIEFDAT_CurrentChanged(object sender, EventArgs e)
        {
            if (dwLIEFDAT == null)
                return;

            DataSet Result = new DataSet();
            Result = m_Data.GetOrderBySupplier(dwLIEFDAT);
            SetData.EKKOPF.Clear();
            SetData.Merge(Result, false, MissingSchemaAction.Add);
        }

        void vwEKKOPF_CurrentChanged(object sender, EventArgs e)
        {
            DataSet Result = new DataSet();
            DataRow dwInput;
            dwInput = dwEKKOPF;
            if (dwInput == null)
            {
                return;
            }
            Result = m_Data.BuildData(dwInput);
            Set4ITX.Clear();
            Set4ITX.Merge(Result, false, MissingSchemaAction.Add);
        }
        public void btnQuery_Click(object sender, EventArgs e)
        {
            DataSet Result = new DataSet();
            DataRow dwInput;
            dwInput = dwEKKOPF;
            int option = 1;
            butSTARTAPP.IsEnabled = false;
            try
            {
                if (dwInput == null)
                {
                    if (LFD.Trim() == "0000000")
                        return;
                    dwInput = SetData.EKPOS.NewRow();
                    dwInput["EKPMANDANT"] = "00";
                    dwInput["EKPAUFKRS"] = KRS;
                    dwInput["EKPAUFLFD"] = LFD;
                }
                if (IsChkALL)//未付款，未确认数量
                {
                    dwInput["EKPBEKZ"] = "' '";
                    IsChkEKPBEKZ = false;
                    IsCheckPayment = false;
                    dwInput["EKPKNTRNRL"] = " ";
                }
                if (IsChkEKPBEKZ)//已经确认数量，未付款
                {
                    dwInput["EKPBEKZ"] = "'N'";
                    IsChkALL = false;
                    IsCheckPayment = true;
                    dwInput["EKPKNTRNRL"] = " ";
                    butSTARTAPP.IsEnabled = true;
                }

                if (IsChkEKPKNTRNRL)//已经付款
                {
                    dwInput["EKPBEKZ"] = "'N'";
                    IsCheckPayment = true;
                    IsChkALL = false;
                    dwInput["EKPKNTRNRL"] = "NOT";
                }
                if (IsChkNoControl)
                {
                    IsChkALL = false;
                    IsChkEKPBEKZ = false;
                    option = 2;
                }
                Result = m_Data.BuildData(dwInput, option);
                Set4ITX.Clear();
                Set4ITX.Merge(Result);
                SetData.EKVRECH.Clear();
                SetData.Merge(Set4ITX.EKVRECH);
                Set4ITX.EKVRECH.Clear();
                if (vwEKPOS.View != null)
                {
                    vwEKPOS.View.MoveCurrentToFirst();
                }
                if (vwTEKKOPF.View != null)
                {
                    vwTEKKOPF.View.MoveCurrentToFirst();
                }
                butSTARTAPP.IsEnabled = true;
                butENDAPP.IsEnabled = false;
                btnPrint.IsEnabled = true;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void StartApply(DataRow dwTemp)
        {
            if (dwTemp == null)
            {
                MessageBox.Show("请选择一条记录");
                return;
            }
            string ordernum = Helpers.Helper.Left(dwTemp["EKPAUFKRS"].ToString() + "-" + dwTemp["EKPAUFLFD"].ToString() + "-" + dwTemp["EKPAUFPOS"].ToString() + "                       ", 23);
            if (dwTemp["EKPBEKZ"].ToString().Trim() != "N")
            {
                //MessageBox.Show(ordernum + " 采购员尚未确认!");
                //return;
            }
            decimal applied = 0;
            decimal toapply = 0;
            if (ToApply.Trim() == "")
                toapply = 0;
            else
            {
                toapply = Convert.ToDecimal(ToApply) * 100;
            }
            var query = from DataRow row in Set4ITX.EKVRECH.AsEnumerable()
                        where row["EKVFILLER"].ToString() == ordernum
                        select row;
            if (query.Count() > 0)
            {
                MessageBox.Show(ordernum + " 不能重复请款!");
                return;
            }

            decimal ekpwe1 = System.Convert.ToDecimal(dwTemp["EKPWE1"].ToString());
            string syear = Helpers.Helper.Right(m_Data.year, 2);
            query = from DataRow row in SetData.EKVRECH.AsEnumerable()
                    where row["EKVFILLER"].ToString() == ordernum
                    select row;
            foreach (DataRow row in query)
            {
                applied += System.Convert.ToDecimal(row["EKVBETRAG"].ToString());
            }
            decimal left = ekpwe1 - applied;
            if (left <= 0)
            {
                MessageBox.Show(ordernum + " 已经完成请款!");
                return;
            }
            if (toapply == 0)
            {
                toapply = ekpwe1 - applied;
            }
            string EKVBELEG = INTEXBL.GetAUFLFD(syear, "EKAUFTR ");
            if (!EKVBELEG.StartsWith(m_Data.month))
            {
                EKVBELEG = m_Data.month + "0001";
                DataRow dwSDDAT = Set4ITX.SDDAT.NewRow();
                dwSDDAT["SDSA"] = "0022";
                dwSDDAT["SDKEY"] = "00EKAUFTR " + syear + "          00";
                dwSDDAT["SDDATEN"] = "BESTELLAUFTR.LFD-NR 0000000000199999999999" + "00000" + m_Data.month + "0001V  0000000" +
                    m_Data.date + "    000000000                                                   " + m_Data.UserID + m_Data.date + "INTEXE  201403040002*";
                m_Data.INTEXDBC.SaveSDDAT(dwSDDAT);
            }
            DataRow dwData = Set4ITX.EKVRECH.NewRow();
            dwData["EKVMANDANT"] = dwTemp["EKPMANDANT"];
            dwData["EKVABLAGE"] = syear;
            dwData["EKVBELEG"] = EKVBELEG;
            dwData["EKVLIEFNR"] = dwTemp["EKPLIEFNR"];
            dwData["EKVRECHNR"] = Helpers.Helper.Left(dwTemp["EKPAUFKRS"].ToString() + "-" + dwTemp["EKPAUFLFD"].ToString() + "           ", 10);
            dwData["EKVBETRAG"] = toapply;
            dwData["EKVWAEHRSL"] = dwTemp["EKPWAEHRSL"];
            dwData["EKVKST"] = "0";
            dwData["EKVEMPF"] = m_Data.UserID;
            dwData["EKVKIR"] = " ";
            dwData["EKVABRECHKZ"] = " ";
            dwData["EKVFILLER"] = ordernum;
            dwData["EKVAENDZL"] = 1;
            dwData["EKVAENDBEN"] = "        ";
            dwData["EKVAENDDAT"] = 0;
            dwData["EKVNEUBEN"] = m_Data.UserID;
            dwData["EKVNEUDAT"] = m_Data.date;
            Set4ITX.EKVRECH.Rows.Add(dwData);
            vwEKPOS.View.MoveCurrentToNext();

        }
        public void cmdStartApply_Click(object sender, EventArgs e)
        {
            try
            {
                if (dwEKPOS["EKPLSCOL"].ToString().Trim() == "Y")
                {
                    MessageBox.Show("请款已经关闭，禁止继续请款");
                    return;
                }
                StartApply(dwEKPOS);
                butSTARTAPP.IsEnabled = true;
                butENDAPP.IsEnabled = true;
                btnPrint.IsEnabled = false;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void cmdStartAllApply_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataRow dwTemp in Set4ITX.ICC_EKPOS.Rows)
                {
                    if (dwTemp["EKPLSCOL"].ToString().Trim() == "Y") continue;
                    StartApply(dwTemp);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        public void cmdEndApply_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataRow row in Set4ITX.EKVRECH.Rows)
                {
                    m_Data.INTEXDBC.SaveEKVRECH(row);
                }
                if (txtLastApp.Text == "Y")
                {
                    dwEKPOS["EKPLSCOL"] = "Y".PadRight(9);
                    INTEXDBC.UpdateEKPOS(dwEKPOS, 9);
                }
                butSTARTAPP.IsEnabled = false;
                butENDAPP.IsEnabled = false;
                btnPrint.IsEnabled = true;
                Set4ITX.EKVRECH.Clear();
                btnQuery_Click(null, null);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void btnPrint_Click(object sender, EventArgs e)
        {
            if (dwTEKKOPF == null)
                return;
            ITXEXRPT.dsSource = Set4ITX;
            ITXEXRPT.dsSource.Merge(SetEnv);
            DataRow dwData;
            DataSet SResult;
            if (IsCheckPayment)
            {
                if (ITXEXRPT.dsSource.Tables.Contains("EKVRECH"))
                {
                    ITXEXRPT.dsSource.Tables["EKVRECH"].Clear();
                }
                dwData = SetData.EKVRECH.NewRow();
                dwData["EKVMANDANT"] = dwTEKKOPF["EKKMANDANT"];
                dwData["EKVRECHNR"] = dwTEKKOPF["EKKAUFKRS"].ToString() + "-" + dwTEKKOPF["EKKAUFLFD"].ToString();
                SResult = INTEXDBC.QueryEKVRECH(dwData, 2);
                ITXEXRPT.dsSource.Merge(SResult);

            }
            string liefnr = dwTEKKOPF["EKKLIEFNR"].ToString();
            string kond = dwTEKKOPF["EKKKONDSL"].ToString();
            string payment = "";
            var qy = from DataRow rx in Set4ITX.Tables["LIEFKO"].AsEnumerable()
                     where rx["LSKLIEFNR"].ToString() == liefnr
                     && rx["LSKKONDSL"].ToString().Trim() == kond.Trim()
                     select rx;
            foreach (DataRow row in qy)
            {
                payment = row["LSKZAHLBED"].ToString();
            }
            dwData = SetData.ZABED.NewRow();
            dwData["ZABMANDANT"] = "00";
            dwData["ZABNR"] = payment;
            SResult = INTEXDBC.QueryZABED(dwData, 1);
            ITXEXRPT.dsSource.Merge(SResult);
            string doc = dwTEKKOPF["EKKBUCHKRS"].ToString().Trim();
            string at = dwTEKKOPF["EKKARTGR"].ToString().Trim();
            string Standard = "YCAEK03DOC";
            switch (doc)
            {
                case "XH":
                    Standard = "YCAEK03DOC";
                    if (at == "5")
                    {
                        Standard = "YCAEK03FP";
                    }
                    break;
                case "PO":
                    Standard = "EK03PO";
                    break;
            }

            ITXEXRPT.IsApplyPayment = IsCheckPayment;
            ITXEXRPT.DocType = Standard;
            ITXEXRPT.strExcelFile = app.company + @"\YCAEK.xls";
            ITXEXRPT.WriteExcelReport();
            Set4ITX.EKVRECH.Clear();
        }
        private void btnSendClick_Click(object sender, RoutedEventArgs e)
        {
            SetDetail.Clear();
            SetDetail.Merge(Set4ITX.EKKOPF);
            SetDetail.Merge(Set4ITX.ABPOS);
            SetDetail.Merge(Set4ITX.WASTAMM);
            SetDetail.Merge(Set4ITX.WAFARBEN);
            SetDetail.Merge(Set4ITX.FSSTAMM);
            SetDetail.Merge(Set4ITX.LIEFDAT);
            if (dwEKPOS == null)
            {
                MessageBox.Show("请选择采购单行");
                return;
            }
            if (dwABAUFM == null)
            {
                MessageBox.Show("请选择留位行");
                return;
            }

            string filter = "EKPART='" + dwEKPOS["EKPART"].ToString() + "'";
            DataRow[] rows = Set4ITX.ICC_EKPOS.Select(filter);
            DataTable tb = rows.CopyToDataTable();
            tb.TableName = "ICC_EKPOS";
            SetDetail.Merge(tb);
            filter = "ABPART='" + dwABAUFM["ABPART"].ToString() + "'";
            rows = Set4ITX.ICC_ABAUFM.Select(filter);
            tb = rows.CopyToDataTable();
            tb.TableName = "ICC_ABAUFM";
            SetDetail.Merge(tb);
            ITXEXRPT.dsSource = SetDetail;
            ITXEXRPT.dsSource.Merge(SetEnv);
            string liefnr = dwTEKKOPF["EKKLIEFNR"].ToString();
            string kond = dwTEKKOPF["EKKKONDSL"].ToString();
            string payment = "";
            var qy = from DataRow rx in Set4ITX.Tables["LIEFKO"].AsEnumerable()
                     where rx["LSKLIEFNR"].ToString() == liefnr
                     && rx["LSKKONDSL"].ToString().Trim() == kond.Trim()
                     select rx;
            foreach (DataRow row in qy)
            {
                payment = row["LSKZAHLBED"].ToString();
            }
            DataRow dwData = SetData.ZABED.NewRow();
            dwData["ZABMANDANT"] = "00";
            dwData["ZABNR"] = payment;
            DataSet SResult = INTEXDBC.QueryZABED(dwData, 1);
            ITXEXRPT.dsSource.Merge(SResult); 

            string Standard = "YCAEKSEND";
            ITXEXRPT.IsApplyPayment = false;
            ITXEXRPT.DocType = Standard;
            ITXEXRPT.strExcelFile = app.company + @"\YCAEK.xls";
            ITXEXRPT.WriteExcelReport();
        }

        private void btnPrintEx_Click(object sender, RoutedEventArgs e)
        {
            if (dwTEKKOPF == null)
                return;
            ITXEXRPT.dsSource = Set4ITX;
            ITXEXRPT.dsSource.Merge(SetEnv);
            DataRow dwData;
            DataSet SResult;
            if (IsCheckPayment)
            {
                if (ITXEXRPT.dsSource.Tables.Contains("EKVRECH"))
                {
                    ITXEXRPT.dsSource.Tables["EKVRECH"].Clear();
                }
                dwData = SetData.EKVRECH.NewRow();
                dwData["EKVMANDANT"] = dwTEKKOPF["EKKMANDANT"];
                dwData["EKVRECHNR"] = dwTEKKOPF["EKKAUFKRS"].ToString() + "-" + dwTEKKOPF["EKKAUFLFD"].ToString();
                SResult = INTEXDBC.QueryEKVRECH(dwData, 2);
                ITXEXRPT.dsSource.Merge(SResult);

            }
            string liefnr = dwTEKKOPF["EKKLIEFNR"].ToString();
            string kond = dwTEKKOPF["EKKKONDSL"].ToString();
            string payment = "";
            var qy = from DataRow rx in Set4ITX.Tables["LIEFKO"].AsEnumerable()
                     where rx["LSKLIEFNR"].ToString() == liefnr
                     && rx["LSKKONDSL"].ToString().Trim() == kond.Trim()
                     select rx;
            foreach (DataRow row in qy)
            {
                payment = row["LSKZAHLBED"].ToString();
            }
            dwData = SetData.ZABED.NewRow();
            dwData["ZABMANDANT"] = "00";
            dwData["ZABNR"] = payment;
            SResult = INTEXDBC.QueryZABED(dwData, 1);
            ITXEXRPT.dsSource.Merge(SResult);
            string Standard = "YCAEK03EXT";
            ITXEXRPT.IsApplyPayment = IsCheckPayment;
            ITXEXRPT.DocType = Standard;
            ITXEXRPT.strExcelFile = app.company + @"\YCAEK.xls";
            ITXEXRPT.WriteExcelReport();
            Set4ITX.EKVRECH.Clear();
        }
    }
}
